﻿@page "/warehouses"
@using Wms.Core.Entities
@inject Wms.Data.WarehouseDbContext DbContext
@inject IJSRuntime JSRuntime

<div class="container-fluid py-4">
    <!-- 页面标题 -->
    <h4 class="text-primary mb-4">
        <span class="oi oi-home me-2"></span> 仓库管理
    </h4>

    <!-- 添加仓库表单 -->
    <div class="card shadow-sm mb-4">
        <div class="card-body">
            <form @onsubmit="HandleAddWarehouse">
                <div class="row g-3 align-items-center">
                    <div class="col-md-6">
                        <input class="form-control form-control-lg" @bind="newWarehouseName" placeholder="请输入新仓库名称" maxlength="50" required />
                    </div>
                    <div class="col-md-4">
                        <input class="form-control form-control-lg" @bind="newWarehouseLocationCount" @bind:event="oninput" type="number" min="0" max="999" placeholder="请输入仓库库位数量" />
                    </div>
                    <div class="col-md-2">
                        <button type="submit" class="btn btn-success btn-lg w-100" disabled="@(string.IsNullOrWhiteSpace(newWarehouseName))">
                            <span class="oi oi-plus me-1"></span> 添加仓库
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- 仓库列表 -->
    <div class="card shadow-sm">
        <div class="card-header bg-white d-flex justify-content-between align-items-center">
            <h6 class="mb-0">仓库列表</h6>
            <span class="badge bg-primary rounded-pill">@warehouses.Count</span>
        </div>
        <div class="card-body p-0">
            @if (!warehouses.Any())
            {
                <div class="text-center py-5">
                    <img src="https://cdn.jsdelivr.net/gh/twbs/icons/icons/building.svg" alt="空仓库" width="48" class="mb-3 opacity-50" />
                    <p class="text-muted">暂无仓库，添加一个吧！</p>
                </div>
            }
            else
            {
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0">
                        <thead class="table-light">
                            <tr>
                                <th scope="col">编号</th>
                                <th scope="col">仓库名称</th>
                                <th scope="col">库位数量</th>
                                <th scope="col" class="text-center" style="width: 150px;">操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach (var w in warehouses)
                            {
                                <tr>
                                    <td><code>@w.Id</code></td>
                                    <td>
                                        <strong>@w.Name</strong>
                                    </td>
                                    <td>
                                        <span class="badge bg-info">@GetLocationCount(w.Id)</span>
                                    </td>
                                    <td class="text-center">
                                        <button class="btn btn-sm btn-outline-danger"
                                        @onclick="() => ConfirmDelete(w.Id, w.Name)"
                                        title="删除仓库">
                                            <span class="oi oi-trash"></span> 删除
                                        </button>
                                    </td>
                                </tr>
                            }
                        </tbody>
                    </table>
                </div>
            }
        </div>
    </div>
</div>

<!-- 删除确认模态框 -->
@if (showDeleteModal)
{
    <div class="modal fade show d-block" tabindex="-1" style="display: block; background: rgba(0,0,0,0.5);">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title text-danger">
                        <span class="oi oi-warning me-2"></span> 确认删除
                    </h5>
                    <button type="button" class="btn-close" @onclick="() => showDeleteModal = false"></button>
                </div>
                <div class="modal-body">
                    <p>确定要删除仓库 <strong>"@deletingWarehouseName"</strong> 吗？</p>
                    <p class="text-danger small">此操作不可撤销！</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" @onclick="() => showDeleteModal = false">取消</button>
                    <button type="button" class="btn btn-danger" @onclick="ExecuteDelete">确认删除</button>
                </div>
            </div>
        </div>
    </div>
}

@code {
    private string newWarehouseName = string.Empty;
    private int? newWarehouseLocationCount = null;
    private List<Warehouse> warehouses = new();

    // 删除模态框相关
    private bool showDeleteModal = false;
    private int deletingWarehouseId;
    private string deletingWarehouseName = string.Empty;

    private int GetLocationCount(int warehouseId)
    {
        return DbContext.Locations.Count(l => l.WarehouseId == warehouseId);
    }

    protected override void OnInitialized()
    {
        warehouses = DbContext.Warehouses.ToList();
    }

    private async Task HandleAddWarehouse()
    {
        if (string.IsNullOrWhiteSpace(newWarehouseName))
            return;

        var trimmedName = newWarehouseName.Trim();

        // 检查是否已存在
        if (warehouses.Any(w => w.Name.Equals(trimmedName, StringComparison.OrdinalIgnoreCase)))
        {
            await JSRuntime.InvokeVoidAsync("alert", "该仓库名称已存在！");
            return;
        }

        var warehouse = new Warehouse { Name = trimmedName };
        DbContext.Warehouses.Add(warehouse);
        DbContext.SaveChanges();
        int locationCount = newWarehouseLocationCount ?? 0;
        // 批量生成库位
        if (locationCount > 0)
        {
            var locations = new List<Location>();
            for (int i = 1; i <= locationCount; i++)
            {
                var code = $"{warehouse.Id}-L{i:D3}"; // 生成如 1-L001, 1-L002
                var name = $"{trimmedName}第{i:D3}号库位";
                locations.Add(new Location
                    {
                        Code = code,
                        Name = name,
                        WarehouseId = warehouse.Id
                    });
            }
            DbContext.Locations.AddRange(locations);
        }

        DbContext.SaveChanges();
        warehouses.Add(warehouse);
        // 提示成功
        await JSRuntime.InvokeVoidAsync("alert", $"仓库 '{trimmedName}' 添加成功，已生成 {newWarehouseLocationCount} 个库位。");
        
        newWarehouseName = string.Empty;
        newWarehouseLocationCount = null;
    }

    private void ConfirmDelete(int id, string name)
    {
        deletingWarehouseId = id;
        deletingWarehouseName = name;
        showDeleteModal = true;
    }

    private async Task ExecuteDelete()
    {
        var warehouse = DbContext.Warehouses.Find(deletingWarehouseId);
        if (warehouse != null)
        {
            DbContext.Warehouses.Remove(warehouse);
            DbContext.SaveChanges();
            warehouses.Remove(warehouse);

            await JSRuntime.InvokeVoidAsync("alert", $"仓库 '{deletingWarehouseName}' 已删除。");
        }
        showDeleteModal = false;
    }
}